package org.jeecg.modules.monitoring.j_monitoring.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.xkcoding.http.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.MPart;
import org.jeecg.modules.monitoring.j_monitoring.entity.MPartImport;
import org.jeecg.modules.monitoring.j_monitoring.service.IMPartService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 备品备件
 * @Author: xiaoyq
 * @Date: 2023-09-11
 * @Version: V1.0
 */
@Api(tags = "备品备件")
@RestController
@RequestMapping("/j_monitoring/mPart")
@Slf4j
public class MPartController extends JeecgController<MPart, IMPartService> {
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param mPart
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "备品备件-分页列表查询")
    @RequiresPermissions("备品备件:查询")
    @ApiOperation(value = "备品备件-分页列表查询", notes = "备品备件-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MPart>> queryPageList(MPart mPart,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                              HttpServletRequest req) {
        QueryWrapper<MPart> queryWrapper = QueryGenerator.initQueryWrapper(mPart, req.getParameterMap());
        if ("已领完".equals(mPart.getUseStatus())) {
            queryWrapper.eq("remainder", 0);
        } else {
            queryWrapper.gt("remainder", 0);
        }
        queryWrapper.orderByAsc("part_name").orderByAsc("remainder");
        Page<MPart> page = new Page<MPart>(pageNo, pageSize);
        IPage<MPart> pageList = service.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mPart
     * @return
     */
    @AutoLog(value = "备品备件-添加")
    @ApiOperation(value = "备品备件-添加", notes = "备品备件-添加")
    @RequiresPermissions("备品备件:添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MPart mPart) {
        mPart.setRemainder(mPart.getTotal());
        mPart.setUseNum(0);
        service.save(mPart);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mPart
     * @return
     */
    @AutoLog(value = "备品备件-编辑")
    @ApiOperation(value = "备品备件-编辑", notes = "备品备件-编辑")
    @RequiresPermissions("备品备件:编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MPart mPart) {
        service.updateById(mPart);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "备品备件-通过id删除")
    @ApiOperation(value = "备品备件-通过id删除", notes = "备品备件-通过id删除")
    @RequiresPermissions("备品备件:删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        service.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "备品备件-批量删除")
    @ApiOperation(value = "备品备件-批量删除", notes = "备品备件-批量删除")
    @RequiresPermissions("备品备件:批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.service.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "备品备件-通过id查询")
    @ApiOperation(value = "备品备件-通过id查询", notes = "备品备件-通过id查询")
    @GetMapping(value = "/queryById")
    @RequiresPermissions("备品备件:查询")
    public Result<MPart> queryById(@RequestParam(name = "id", required = true) String id) {
        MPart mPart = service.getById(id);
        if (mPart == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mPart);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mPart
     */
    //@RequiresPermissions("org.jeecg.modules.monitoring:备品备件:exportXls")
    @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
    @ApiOperation(value="备品备件-导出", notes="备品备件-导出")
    @RequiresPermissions("备品备件:导出")
    public ModelAndView exportXls(HttpServletRequest request, MPart mPart) {
        return super.exportXls(request, mPart, MPart.class, "备品备件");
    }

    @RequestMapping(value = "/exportTemplate")
    @RequiresPermissions("备品备件:导出")
    public ModelAndView exportTemplate(HttpServletRequest request, MPartImport mPart) {


        List<MPartImport> list = new ArrayList<>();
        mPart.setPartName("备件名称");
        mPart.setConfiguration("型号/配置");
        mPart.setTotal(100);
        list.add(mPart);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String title = "模板";
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, MPartImport.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;

    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("备品备件:importExcel")
    @ApiOperation(value="备品备件-导入", notes="备品备件-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @RequiresPermissions("备品备件:导入")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MPart.class);
    }

    @RequestMapping(value = "/importTemplate", method = RequestMethod.POST)
    @RequiresPermissions("备品备件:导入")
    public Result<?> importTemplate(HttpServletRequest request, HttpServletResponse response) {

        Map<String, String[]> reqMap = request.getParameterMap();
        String contractId = reqMap.get("contractId")==null ? "" : reqMap.get("contractId")[0];
        String contractName = reqMap.get("contractName")==null ? "" : reqMap.get("contractName")[0];


        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MPart> list = ExcelImportUtil.importExcel(file.getInputStream(), MPart.class, params);
                for (MPart part : list){
                    part.setUseNum(0);
                    part.setRemainder(part.getTotal());
                    part.setContractId(contractId);
                    part.setContractName(contractName);
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                service.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


    @RequestMapping(value = "/testImport", method = RequestMethod.GET)
    public void testImport() {
        service.test();
    }

    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    @RequiresPermissions("备品备件:查询")
    public Result queryByIds(@RequestParam(value = "ids[]") String[] ids ,HttpServletRequest req) {

        QueryWrapper<MPart> queryWrapper = QueryGenerator.initQueryWrapper(new MPart(), req.getParameterMap());
        queryWrapper.in("id",ids);
        queryWrapper.orderByAsc("part_name").orderByAsc("remainder");
        List<MPart> list = service.list(queryWrapper);
        return Result.OK(list);
    }

}
